<template>
    <div class="img-list-picker">
        <van-uploader
            class="uploader"
            ref="uploader"
            :max-count="9"
            :multiple="true"
            :after-read="afterRead"
        >
            <template>
                <div class="preview-cover van-ellipsis">
                    <img :src="imgUrl" />
                </div>
            </template>
        </van-uploader>
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: String
        }
    },
    data() {
        return {
            file: null,
            imgUrl: "",
            files: []
        };
    },

    methods: {
        afterRead(files) {
            // 直选择单个文件，转化数组
            if (!files.length) {
                let file = files;
                files = [];
                files.push(file);
            }

            // 预览图片
            let previewImages = files.map(f => {
                return f.content;
            });

            this.files = files.map(f => {
                return f.file;
            });
            console.log("afterRead", files, previewImages);
            this.$emit("change", previewImages);
        },

        uploadImages() {
            console.log("准备上传的文件", this.files);
            return this.$cloudApi.uploadFiles(this.files);
        },

        getTempFile() {
            this.$cloud
                .getTempFileURL({
                    fileList: [this.value]
                })
                .then(res => {
                    res.fileList.forEach(el => {
                        if (el.code === "SUCCESS") {
                            // console.log(el.tempFileURL);
                            this.imgUrl = el.tempFileURL;
                        } else {
                            //获取下载链接失败
                            this.$showToast("图片加载失败");
                        }
                    });
                });
        },

        chooseFile() {
            const uploaderComp = this.$refs.uploader;
            uploaderComp.chooseFile();
        }
    }
};
</script>


<style lang="less" scoped>
.img-list-picker {
    display: inline-block;
    overflow: hidden;
    height: 100px;
    .uploader {
        visibility: hidden;
    }

    .preview-cover {
        position: relative;
        width: 100px;
        height: 100px;
        overflow: hidden;
        background: #eee;
        border-radius: 12px;

        img {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translateX(-50%) translateY(-50%);
        }
    }
}
</style>
